package com.aaa.ms.service.impl;

import com.aaa.common.util.Result;
import com.aaa.common.util.ResultStatus;
import com.aaa.ms.service.RemoteProductService;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

/**
 * @ fileName:RemoteProductServiceImpl
 * @ description:
 * @ author:zhz
 * @ createTime:2023/6/9 11:43
 * @ version:1.0.0
 */
@Service
public class RemoteProductServiceImpl implements RemoteProductService {

    @Resource
    private RestTemplate restTemplate;

    //fallback  B计划  兜底方法  远程方法遇到任何异常，都可以执行B计划
    @Override
    @SentinelResource(value = "SentinelResourceQueryById",
            blockHandler = "queryByIdBlockHandler",
    fallback = "queryByIdFallback")    //埋点  这个位置调用远程
    public Result queryById(long productId) {
        if(productId==2){
            throw  new NullPointerException();
        }
        return restTemplate.getForObject("http://GoodsServer/product/queryById?id="+productId, Result.class);
    }

    /**
     * sentinel处理远程方法限流
     * @param productId
     * @param be
     * @return
     */
    public Result queryByIdBlockHandler(long productId, BlockException be){
          return new Result(ResultStatus.REMOTE_METHOD_LIMIT.getReturnCode(),
                  ResultStatus.REMOTE_METHOD_LIMIT.getReturnMsg(),be.getClass().getName());
    }

    /**
     * sentinel处理远程方法异常
     * @param productId
     * @return
     */
    public Result queryByIdFallback(long productId,Throwable t){
        return new Result(ResultStatus.REMOTE_METHOD_ERROR.getReturnCode(),
                ResultStatus.REMOTE_METHOD_ERROR.getReturnMsg(),t.getClass().getName());
    }
}
